package com.ruoyi.doctor.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.doctor.mapper.DoctorFollowMapper;
import com.ruoyi.doctor.domain.DoctorFollow;
import com.ruoyi.doctor.service.IDoctorFollowService;

/**
 * 医生关注管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-13
 */
@Service
public class DoctorFollowServiceImpl implements IDoctorFollowService 
{
    @Autowired
    private DoctorFollowMapper doctorFollowMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询医生关注管理
     * 
     * @param id 医生关注管理主键
     * @return 医生关注管理
     */
    @Override
    public DoctorFollow selectDoctorFollowById(Long id)
    {
        return doctorFollowMapper.selectDoctorFollowById(id);
    }

    /**
     * 查询医生关注管理列表
     * 
     * @param doctorFollow 医生关注管理
     * @return 医生关注管理
     */
    @Override
    public List<DoctorFollow> selectDoctorFollowList(DoctorFollow doctorFollow)
    {
        return doctorFollowMapper.selectDoctorFollowList(doctorFollow);
    }

    /**
     * 新增医生关注管理
     * 
     * @param doctorFollow 医生关注管理
     * @return 结果,关注医生 → followCount +1
     */
    @Override
    public int insertDoctorFollow(DoctorFollow doctorFollow)
    {
        // 构造查询条件
        DoctorFollow query = new DoctorFollow();
        query.setPatientId(doctorFollow.getPatientId());
        query.setDoctorId(doctorFollow.getDoctorId());
        // 查询是否已存在
        List<DoctorFollow> list = doctorFollowMapper.selectDoctorFollowList(query);
        if (list != null && !list.isEmpty()) {
            throw new RuntimeException("该患者已关注过该医生");
        }
        // 2. 原有逻辑：插入关注关系
        int result = doctorFollowMapper.insertDoctorFollow(doctorFollow);
        // 3. Redis：医生关注量 +1
        String doctorKey = "doctor:follow:count:" + doctorFollow.getDoctorId();
        redisTemplate.opsForValue().increment(doctorKey, 1);
        // 4. 构造延迟同步任务：1 小时后同步 +1 到数据库的 doctor.followCount
        long delaySeconds = 3600;
        long executeTime = System.currentTimeMillis() / 1000 + delaySeconds;
        Map<String, Object> syncTask = new HashMap<>();
        syncTask.put("doctorId", doctorFollow.getDoctorId());
        syncTask.put("changeCount", 1); // +1 表示关注
        syncTask.put("operateTime", String.valueOf(System.currentTimeMillis()));
        syncTask.put("patientId", doctorFollow.getPatientId());


        try {
            String taskJson = objectMapper.writeValueAsString(syncTask);
            redisTemplate.opsForZSet().add(
                    "doctor:follow:delay:sync", // ZSET key
                    taskJson,
                    executeTime
            );
        } catch (Exception e) {
            e.printStackTrace(); // 实际请使用日志框架
        }

        return result;
    }

    /**
     * 修改医生关注管理
     * 
     * @param doctorFollow 医生关注管理
     * @return 结果
     */
    @Override
    public int updateDoctorFollow(DoctorFollow doctorFollow)
    {
        return doctorFollowMapper.updateDoctorFollow(doctorFollow);
    }

    /**
     * 批量删除医生关注管理
     * 
     * @param ids 需要删除的医生关注管理主键
     * @return 结果
     */
    @Override
    public int deleteDoctorFollowByIds(Long[] ids)
    {

        return doctorFollowMapper.deleteDoctorFollowByIds(ids);
    }

    /**
     * 删除医生关注管理信息
     * 
     * @param id 医生关注管理主键
     * @return 结果,取消关注 → followCount -1
     */
    @Override
    public int deleteDoctorFollowById(Long id)
    {
        // 1. 查询该关注记录，获取 doctorId 和 patientId
        DoctorFollow follow = doctorFollowMapper.selectDoctorFollowById(id);
        if (follow == null) {
            throw new RuntimeException("未找到对应的关注记录");
        }
        Long doctorId = follow.getDoctorId();
        Long patientId = follow.getPatientId();
        // 2. 删除关注关系
        int result = doctorFollowMapper.deleteDoctorFollowById(id);
        // 3. Redis：该医生的 followCount -1（实时减少）
        String doctorKey = "doctor:follow:count:" + doctorId;
        redisTemplate.opsForValue().increment(doctorKey, -1);

        // 4. 构造延迟同步任务：1 小时后同步 -1 到数据库的 doctor.followCount
        long delaySeconds = 3600;
        long executeTime = System.currentTimeMillis() / 1000 + delaySeconds;

        Map<String, Object> syncTask = new HashMap<>();
        syncTask.put("doctorId", doctorId);
        syncTask.put("changeCount", -1); // -1 表示取消关注
        syncTask.put("operateTime", String.valueOf(System.currentTimeMillis()));
        syncTask.put("patientId", patientId);

        try {
            String taskJson = objectMapper.writeValueAsString(syncTask);
            redisTemplate.opsForZSet().add(
                    "doctor:follow:delay:sync",
                    taskJson,
                    executeTime
            );
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
